use crate::routers::get_userid_from_jwt;
use crate::search_engine::{get_search_engine_file, get_search_engine_paper};
use crate::{
    app_writer::{AppResult, AppWriter},
    dtos::{
        files::FileResponse,
        paper::PaperResponse,
        search::SearchRequest,
    }
};
use salvo::Writer;
use salvo::{
    oapi::{
        endpoint,
        extract::JsonBody,
    },
    Depot
};
use validator::Validate;

#[endpoint(tags("search"))]
pub async fn get_search_paper(
    req: JsonBody<SearchRequest>,
    depot: &mut Depot,
) -> AppResult<AppWriter<Vec<PaperResponse>>> {
    req.0.validate()?;
    let user_id = get_userid_from_jwt(depot)?;
    let search_engine = get_search_engine_paper().await?;
    let res = search_engine.search(req.0, user_id).await?;
    let res = AppWriter(Ok(res));
    Ok(res)
}

#[endpoint(tags("search"))]
pub async fn get_search_file(
    req: JsonBody<SearchRequest>,
    depot: &mut Depot,
) -> AppResult<AppWriter<Vec<FileResponse>>> {
    req.0.validate()?;
    let user_id = get_userid_from_jwt(depot)?;
    let search_engine = get_search_engine_file().await?;
    let res = search_engine.search(req.0, user_id).await?;
    let res = AppWriter(Ok(res));
    Ok(res)
}
